package com.ailk.kbi.kbiwarden.wsi.util

import com.ailk.kbi.kbiwarden.wsi.exception.WSI_ERROR;
import com.ailk.kbi.kbiwarden.wsi.exception.WsiException;
import com.ailk.kbi.kbiwarden.wsi.type.request.AuthInfoType;



class SystemUtil {
	public static final String SETTING_FILE = "config.xml";
	def configXML
	SystemUtil(){
		configXML = new XmlSlurper().parse(Thread.currentThread().getContextClassLoader().getResource(SETTING_FILE).getFile())
	}
	
	public static String getWebRoot(){
		String webRoot = (new File(Thread.currentThread().getContextClassLoader().getResource(SystemUtil.SETTING_FILE).getPath())).getParentFile().getParentFile().getAbsolutePath()
		if(webRoot.indexOf("/") > 0 && !webRoot.endsWith("/")){
			webRoot = webRoot + "/"
		}
		
		if(webRoot.indexOf("\\") > 0 && !webRoot.endsWith("\\")){
			webRoot = webRoot + "\\"
		}
		webRoot
	}
	
	void login(AuthInfoType loginVO) {
		def userXML = configXML.users.user.find{ it.@userName == loginVO.userName &&  it.@password == loginVO.password}
		if(!userXML){
			throw new WsiException(WSI_ERROR.ER_001_AUTHENTICATION)
		}		
	}
	
	void security(String userName, String operationName){
		def operationXML = getOperationXML(operationName)
		def userXML = operationXML.security.user.find{it.@userName == userName}
		if(!userXML){
			throw new WsiException(WSI_ERROR.ER_002_AUTHORITY)
		}
	}
	
	String getTable(String operationName){
		def operationXML = getOperationXML(operationName)
		
		String table = operationXML.table
		if(!table){
			throw new WsiException(WSI_ERROR.ER_002_AUTHORITY)
		}
		table
	}
	
	String getSchema(String operationName){
		def operationXML = getOperationXML(operationName)
		
		String schema = operationXML.schema
		if(!schema){
			throw new WsiException(WSI_ERROR.ER_002_AUTHORITY)
		}
		schema
	}
	
	def getOperationXML(String operationName){
		def operationXML = configXML.operations.operation.find{it.@name == operationName}
		if(operationXML){
			return operationXML
		}
		else{
			throw new WsiException(WSI_ERROR.ER_002_AUTHORITY)
		}
	}
	
	String getDbsURL(){
		configXML.datasource.url
	}
	
	String getDbsUser(){
		configXML.datasource.user
	}
	
	String getDbsPassword(){
		configXML.datasource.password
	}
	
}
